package com.wg.photo.activity;

import android.content.Intent;
import android.provider.MediaStore;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.wg.photo.ABSOnItemClickListener;
import com.wg.photo.BaseActivity;
import com.wg.photo.PictureListener;
import com.wg.photo.R;
import com.wg.photo.adapter.RVChoosePictureGlideStringAdapter;
import com.wg.photo.utils.GroupImage;
import com.wg.photo.utils.PickConfig;
import com.wg.photo.utils.PickPhotoHelper;
import com.wg.photo.utils.PickPreferences;
import com.wg.photo.utils.PickUtils;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class ChoosePictureActivity extends BaseActivity {
    private static final String TAG = "ChoosePictureActivity";
    private List<String> allPhotos = new ArrayList<>();
    private RecyclerView mRVpicture;
    private RequestManager manager;
    private ImageView mIVmenu;
    private static final int PCITURE_LIST = 0x56;
    private RVChoosePictureGlideStringAdapter mAdapter;
    private TextView mTVcounts,mTVsubmit,mTVtitle;

    @Override
    public int getLayoutId() {
        return R.layout.activity_choose_picture;
    }

    @Override
    public void initViews() {
        manager = Glide.with(this);
        mRVpicture = (RecyclerView) findViewById(R.id.act_choose_picture_RV);
        mTVcounts = (TextView) findViewById(R.id.act_choose_picture_TV_counts);
        mTVsubmit = (TextView) findViewById(R.id.act_choose_picture_TV_submit);
        mTVtitle = (TextView) findViewById(R.id.act_choose_picture_TV_title);
        mIVmenu = (ImageView) findViewById(R.id.act_choose_picture_IV_menu);
        mRVpicture.setLayoutManager(new GridLayoutManager(this,4,GridLayoutManager.VERTICAL,false));
        mAdapter = new RVChoosePictureGlideStringAdapter(this,allPhotos,manager);
        mRVpicture.setAdapter(mAdapter);

        PickPhotoHelper helper = new PickPhotoHelper(ChoosePictureActivity.this, new PictureListener() {
            @Override
            public void onSuccess() {
                GroupImage groupImage = PickPreferences.getInstance(ChoosePictureActivity.this).getListImage();
                allPhotos.clear();
                allPhotos.addAll(groupImage.mGroupMap.get(PickConfig.ALL_PHOTOS));
                if(allPhotos == null){
                    Log.e("PickPhotoView","Image is Empty");
                }else {
                    Log.e("All photos size:", String.valueOf(allPhotos.size()));
                }
                if (allPhotos != null && !allPhotos.isEmpty()) {
//                    pickGridAdapter = new PickGridAdapter(PickPhotoActivity.this, manager, allPhotos, pickData.isShowCamera(), pickData.getSpanCount(), pickData.getPickPhotoSize(), imageClick);
//                    photoList.setAdapter(pickGridAdapter);
//                    mAdapter = new RVChoosePictureStringAdapter(allPhotos);

//                    RVChoosePictureGlideStringAdapter mAdapter = new RVChoosePictureGlideStringAdapter(allPhotos,manager);
                    mAdapter.notifyDataSetChanged();
//                    DirImage dirImage = PickPreferences.getInstance(ChoosePictureActivity.this).getDirImage();
//                    String dirName = dirImage.dirName.get(position);
//                    mTVtitle.setText(groupImage.mGroupMap);
                }
            }
        });
        helper.getImages();
    }

    @Override
    public void setListeners() {
        mRVpicture.addOnScrollListener(scrollListener);
        mIVmenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ChoosePictureActivity.this,PickListActivity.class);
                startActivityForResult(intent, PickConfig.LIST_PHOTO_DATA);
//                startActivity();
            }
        });
        mAdapter.setAbsOnItemClickListener(new ABSOnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                String imgPath = mAdapter.getItem(position);
                Intent intent = new Intent();
                intent.setClass(ChoosePictureActivity.this, PicturePreviewActivity.class);
                intent.putExtra(PickConfig.INTENT_IMG_PATH, imgPath);
                intent.putExtra(PickConfig.INTENT_IMG_LIST, (Serializable) allPhotos);
                intent.putExtra(PickConfig.INTENT_IMG_LIST_SELECT, (Serializable) mAdapter.getSelectPath());
//            intent.putExtra(PickConfig.INTENT_PICTURE_DATA,pickData);
                startActivityForResult(intent,PickConfig.PREVIEW_PHOTO_DATA);
            }

            @Override
            public void add() {
                try {
                    File photoFile = PickUtils.getInstance(ChoosePictureActivity.this).getPhotoFile();
                    if (photoFile.exists()) {
                        photoFile.delete();
                    }
                    if (photoFile.createNewFile()) {
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, PickUtils.getInstance(ChoosePictureActivity.this).getUri(photoFile));
                        ChoosePictureActivity.this.startActivityForResult(intent, PickConfig.CAMERA_PHOTO_DATA);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void selected(int position) {
                if (!mAdapter.selectPath(mAdapter.getItem(position))){
                    Toast.makeText(ChoosePictureActivity.this, "只能选9张", Toast.LENGTH_SHORT).show();
                    return;
                }

                mAdapter.notifyItemChanged(mAdapter.isShowCamera()?position+1:position);
                mTVcounts.setText(mAdapter.getSelectPath().size()+"");
            }
        });

        mTVsubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mAdapter.getSelectPath().isEmpty()){
                    Intent intent = getIntent();
                    intent.putExtra(PickConfig.INTENT_PICTURE_DATA, (Serializable) mAdapter.getSelectPath());
                    setResult(RESULT_OK,intent);
                    ChoosePictureActivity.this.finish();
                }
            }
        });
    }


    RecyclerView.OnScrollListener scrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if (Math.abs(dy) > PickConfig.SCROLL_THRESHOLD) {
                manager.pauseRequests();
            } else {
                manager.resumeRequests();
            }
        }

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                manager.resumeRequests();
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 0) {
            return;
        }
        if (requestCode == PickConfig.LIST_PHOTO_DATA) {
            if (data != null) {
                String dirName = data.getStringExtra(PickConfig.INTENT_DIR_NAME);
                GroupImage listImage = PickPreferences.getInstance(ChoosePictureActivity.this).getListImage();
                mTVtitle.setText(dirName);
                allPhotos.clear();
                allPhotos.addAll(listImage.mGroupMap.get(dirName));
                mAdapter.updateData(allPhotos);
            }
        } else if (requestCode == PickConfig.CAMERA_PHOTO_DATA) {
            String path;
            if (data != null) {
                path = data.getData().getPath();
                if (path.contains("/pick_camera")) {
                    path = path.replace("/pick_camera", "/storage/emulated/0/DCIM/Camera");
                }
            } else {
                path = PickUtils.getInstance(ChoosePictureActivity.this).getFilePath();
            }
            allPhotos.add(0,path);
            mAdapter.notifyDataSetChanged();
        }else if(requestCode == PickConfig.PREVIEW_PHOTO_DATA){
            if (data != null) {
                List<String> compPath = new ArrayList<>();
                List<String> selectPath = (List<String>) data.getSerializableExtra(PickConfig.INTENT_IMG_LIST_SELECT);
                mAdapter.setSelectPath(selectPath);
                mAdapter.notifyDataSetChanged();
                mTVcounts.setText(mAdapter.getSelectPath().size()+"");
               /* for (int i = 0; i < selectPath.size(); i++) {
                    File file = new File(selectPath.get(i));
                    String s = FileUtil.saveBitmapFile(file, getPackageName() + "/imge", file.getName());
                    compPath.add(s);
                }
                for (int i = 0; i < compPath; i++) {

                }*/
//                mAdapter.setSelectPath(selectPath);
//                pickGridAdapter.notifyDataSetChanged();
//                updateSelectText(String.valueOf(selectPath.size()));
            }
        }
    }
}
